package com.qinglei.recoup.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinglei.recoup.common.domain.RadarMessage;
import com.qinglei.recoup.common.domain.RadarUserDataFour;
import com.qinglei.recoup.common.exception.RedisConnectException;
import com.qinglei.recoup.common.service.RedisService;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.system.dao.RadarUserDataFourMapper;
import com.qinglei.recoup.system.domain.Bed;
import com.qinglei.recoup.system.domain.BedRadarBO;
import com.qinglei.recoup.system.domain.Event;
import com.qinglei.recoup.system.domain.RealTimeMonitoring;
import com.qinglei.recoup.system.pojo.RealTimeDataVOV4;
import com.qinglei.recoup.system.pojo.event.EventDto;
import com.qinglei.recoup.system.pojo.event.VitalSignsAlarmDto;
import com.qinglei.recoup.system.service.*;
import com.qinglei.recoup.system.util.ProducerInstance;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @author dqh
 */
@Service
@Slf4j
public class RadarUserDataFourServiceImpl extends ServiceImpl<RadarUserDataFourMapper, RadarUserDataFour> implements RadarUserDataFourService {

    @Autowired
    private BedService bedService;

    @Autowired
    private RealTimeMonitoringService realTimeMonitoringService;

    @Autowired
    private DeviceRealTimeDataService deviceRealTimeDataService;
    @Value("${alarm-event-topic}")
    private String alarmTopic;
    @Value("${alarm-event-group}")
    private String alarmGroup;
    @Value("${device-event-topic}")
    private String deviceTopic;
    @Value("${device-event-group}")
    private String deviceGroup;
    @Value("${rocketmq.name-server}")
    private String rocketServer;
    @Autowired
    private EventService eventService;
    @Autowired
    private RedisService redisService;

    public static final int STATUS_NORMAL = 1;
    public static final int STATUS_OUT_BED = 2;
    public static final int STATUS_RADAR_OFFLINE = 3;
    public static final int STATUS_MONITOR_OFF = 4;

    public static final int SUB_STATUS_CLEAR = 1;
    public static final int SUB_STATUS_LIGHT = 2;
    public static final int SUB_STATUS_DEEP = 3;

    @Override
    public void saveRadarUserData(RadarMessage message) throws MQBrokerException, RemotingException, InterruptedException, MQClientException, RedisConnectException {

        RadarUserDataFour radarUserDataFour = (RadarUserDataFour) message.getData();
        //UploadResult.TooCloseFlag
        Integer TCFg = radarUserDataFour.getTCFg(); //目标过近标志（布尔型标量，1 表示过近，0 表示正常）

        //UploadResult.OutBedFlag
        Integer OBFg = radarUserDataFour.getOBFg(); //离床标志（布尔型标量，1 表示离床，0 表示在床）
        //UploadResult.TargetSteadyFlag
        Integer TSFg = radarUserDataFour.getTSFg(); //（布尔型标量，1 表示配合，0 表示非配合）

//        if(TCFg==1||OBFg==1||TSFg==0){
//            return;
//        }

        radarUserDataFour.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        this.getBaseMapper().insert(radarUserDataFour);
        MQProducer realDataProducer = ProducerInstance.getProducerInstance().getInstance(rocketServer, deviceGroup);
        Message realDataMsg = new Message(deviceTopic, JSON.toJSONString(radarUserDataFour).getBytes(StandardCharsets.UTF_8));
        realDataProducer.sendOneway(realDataMsg);
        //处理心跳、呼吸报警
        //判断当前床是否有人
        if (OBFg == 0) {
            Date now = new Date();
            // 心跳值
            int hrbpRe = radarUserDataFour.getHRBpRe() == null ? 0 : radarUserDataFour.getHRBpRe().intValue();
            // 呼吸值
            int breBp = radarUserDataFour.getBrebp() == null ? 0 : radarUserDataFour.getBrebp().intValue();
            Collection<VitalSignsAlarmDto> vitalSignsAlarmDtos = deviceRealTimeDataService.getVitalSignsAlarmBySn(radarUserDataFour.getSn(), now);
            if (CollectionUtils.isNotEmpty(vitalSignsAlarmDtos)) {
                //生命体征报警类别(1.离床过久2.跌倒3.呼吸过速4.呼吸暂停过久5.心跳过缓6.心跳过速)
                LocalDateTime localDateTime = LocalDateTime.now();
                Event event = new Event();
                event.setUserId(0L);
                event.setHappenTime(localDateTime);
                event.setCreateTime(localDateTime);
                event.setModifyTime(localDateTime);
                event.setTenantId(1);
                for (VitalSignsAlarmDto vitalSginsAlarmDto : vitalSignsAlarmDtos) {
                    MQProducer producer = ProducerInstance.getProducerInstance().getInstance(rocketServer, alarmGroup);
//                    DefaultMQProducer producer = new DefaultMQProducer(alarmGroup);
                    event.setBedId(vitalSginsAlarmDto.getBedId());
                    if (1 == vitalSginsAlarmDto.getSignType()) {
                        if ("是".equals(vitalSginsAlarmDto.getLcbz())) {
                            if (StringUtils.isBlank(redisService.get(message.getSn() + "QLDGJSJLCGJ"))) {
                                redisService.set(message.getSn() + "QLDGJSJLCGJ", "1");
                                //离床过久
                                EventDto eventDto = new EventDto(1, vitalSginsAlarmDto.getBedName(), message.getSn(), now, "离床过久报警");
                                eventDto.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                                String fsMsg = JSON.toJSONString(eventDto);
                                log.info("离床过久报警  推送日志  msg:{}  topic:{}  group:{}", fsMsg, alarmTopic, alarmGroup);
                                Message msg = new Message(alarmTopic, fsMsg.getBytes(StandardCharsets.UTF_8));
                                producer.sendOneway(msg);
                                event.setType(1);
                                event.setContent("离床过久报警");
                                eventService.save(event);
                            }
                        } else {
                            redisService.del(message.getSn() + "QLDGJSJLCGJ");
                        }
                    }
                    if (3 == vitalSginsAlarmDto.getSignType()) {
                        if ("是".equals(vitalSginsAlarmDto.getHxgs())) {
                            if (StringUtils.isBlank(redisService.get(message.getSn() + "QLDGJSJHXGS"))) {
                                redisService.set(message.getSn() + "QLDGJSJHXGS", "1");
                                //呼吸过速
                                EventDto eventDto = new EventDto(3, vitalSginsAlarmDto.getBedName(), message.getSn(), now, "呼吸过速报警");
                                eventDto.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                                String fsMsg = JSON.toJSONString(eventDto);
                                log.info("呼吸过速报警  推送日志  msg:{}  topic:{}  group:{}", fsMsg, alarmTopic, alarmGroup);
                                Message msg = new Message(alarmTopic, fsMsg.getBytes(StandardCharsets.UTF_8));
                                producer.sendOneway(msg);
                                event.setType(3);
                                event.setContent("呼吸过速报警");
                                eventService.save(event);
                            }
                        } else {
                            redisService.del(message.getSn() + "QLDGJSJHXGS");
                        }
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String scyz = redisService.get(message.getSn() + "QLDGJSJHXZTGJ");
                    if (4 == vitalSginsAlarmDto.getSignType()) {
                        if ("是".equals(vitalSginsAlarmDto.getHxgh())) {
                            if (StringUtils.isBlank(scyz)) {
                                redisService.set(message.getSn() + "QLDGJSJHXZTGJ", vitalSginsAlarmDto.getContinued());
                                //呼吸暂停过久报警
                                EventDto eventDto = new EventDto(4, vitalSginsAlarmDto.getBedName(), message.getSn(), now, "呼吸暂停过久报警");
                                eventDto.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                                String fsMsg = JSON.toJSONString(eventDto);
                                log.info("呼吸暂停过久报警  推送日志  msg:{}  topic:{}  group:{}", fsMsg, alarmTopic, alarmGroup);
                                Message msg = new Message(alarmTopic, fsMsg.getBytes(StandardCharsets.UTF_8));
                                producer.sendOneway(msg);
                                event.setType(4);
                                event.setContent("呼吸暂停过久报警");
                                eventService.save(event);
                            }
                            if (StringUtils.isBlank(redisService.get(message.getSn() + "QLDGJSJHXZTGJSTARTTIME"))) {
                                redisService.set(message.getSn() + "QLDGJSJHXZTGJCXCJ", sdf.format(now));
                            }
                        } else {
                            String startTime = redisService.get(message.getSn() + "QLDGJSJHXZTGJSTARTTIME");
                            if (StringUtils.isNotBlank(scyz) && StringUtils.isNotBlank(startTime)) {
                                try {
                                    int scends = calLastedTime(sdf.parse(startTime), now);
                                    scends = scends + Integer.parseInt(scyz);
                                    EventDto eventDto = new EventDto(20, vitalSginsAlarmDto.getBedName(), message.getSn(), now, "心跳暂停过久报警解除", scends + "");
                                    eventDto.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                                    Message msg = new Message(alarmTopic, JSON.toJSONString(eventDto).getBytes(StandardCharsets.UTF_8));
                                    producer.sendOneway(msg);
                                } catch (ParseException e) {
                                    log.info("推送呼吸暂停过久报警解除异常  参数====>" + startTime + "、" + scyz);
                                    e.printStackTrace();
                                }
                                redisService.del(message.getSn() + "QLDGJSJHXZTGJSTARTTIME");
                                redisService.del(message.getSn() + "QLDGJSJHXZTGJ");
                            }
                        }
                    }
                    if (5 == vitalSginsAlarmDto.getSignType()) {
                        if ("是".equals(vitalSginsAlarmDto.getXtgh())) {
                            if (StringUtils.isBlank(redisService.get(message.getSn() + "QLDGJSJXTGH"))) {
                                redisService.set(message.getSn() + "QLDGJSJXTGH", "1");
                                //心跳过缓
                                EventDto eventDto = new EventDto(7, vitalSginsAlarmDto.getBedName(), message.getSn(), now, "心跳过缓报警");
                                eventDto.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                                String fsMsg = JSON.toJSONString(eventDto);
                                log.info("呼吸暂停过久报警  推送日志  msg:{}  topic:{}  group:{}", fsMsg, alarmTopic, alarmGroup);
                                Message msg = new Message(alarmTopic, fsMsg.getBytes(StandardCharsets.UTF_8));
                                producer.sendOneway(msg);
                                event.setType(5);
                                event.setContent("心跳过缓报警");
                                eventService.save(event);
                            }
                        } else {
                            redisService.del(message.getSn() + "QLDGJSJXTGH");
                        }
                    }
                    if (6 == vitalSginsAlarmDto.getSignType()) {
                        if ("是".equals(vitalSginsAlarmDto.getXtgs())) {
                            if (StringUtils.isBlank(redisService.get(message.getSn() + "QLDGJSJXTGS"))) {
                                redisService.set(message.getSn() + "QLDGJSJXTGS", "1");
                                //心跳过速
                                EventDto eventDto = new EventDto(6, vitalSginsAlarmDto.getBedName(), message.getSn(), now, "心跳过速报警");
                                eventDto.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                                String fsMsg = JSON.toJSONString(eventDto);
                                log.info("心跳过速报警  推送日志  msg:{}  topic:{}  group:{}", fsMsg, alarmTopic, alarmGroup);
                                Message msg = new Message(alarmTopic, fsMsg.getBytes(StandardCharsets.UTF_8));
                                producer.sendOneway(msg);
                                event.setType(6);
                                event.setContent("心跳过速报警");
                                eventService.save(event);
                            }
                        } else {
                            redisService.del(message.getSn() + "QLDGJSJXTGS");
                        }
                    }
                }
            }
        }
    }

    /**
     * 计算两个日期相差的秒数
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public int calLastedTime(Date startDate, Date endDate) {
        long a = endDate.getTime();
        long b = startDate.getTime();
        int c = (int) ((a - b) / 1000);
        return c;
    }

    @Override
    public RealTimeDataVOV4 getRealTimeData(Integer bedId, Integer second, Integer tenantId) throws RedisConnectException {
        if (second == null) {
            second = 0;
        }
        BedRadarBO bedRadarBO = bedService.getBedWithSn(bedId);
        if (bedRadarBO == null) {
            return null;
        }
        RealTimeDataVOV4 realTimeDataVOV4 = new RealTimeDataVOV4();
        List<RadarUserDataFour> radarUserDataList = this.getBaseMapper().selectRadarUserDataFourData(bedRadarBO.getSnCode(), second);
        this.setStatus(bedRadarBO, realTimeDataVOV4);
        List<String> radarUserDataList60 = this.getBaseMapper().selectRadarUserDataFourData60(bedRadarBO.getSnCode(), second);
        if (CollectionUtils.isNotEmpty(radarUserDataList) && radarUserDataList.size() == 20) {
            RadarUserDataFour radarUserDataFour = radarUserDataList.get(0);
            Integer TCFg = radarUserDataFour.getTCFg(); // 1 表示过近，0 表示正常
            Integer OBFg = radarUserDataFour.getOBFg(); //1 表示离床，0 表示在床
            if (OBFg != 1) {
                List<Double> heartPhaseData = new ArrayList<>(200);
                List<Double> breathPhaseData = new ArrayList<>(200);
                for (int i = 0; i < radarUserDataList.size(); i++) {
                    RadarUserDataFour radarUserDataFourTmp = radarUserDataList.get(radarUserDataList.size() - 1 - i);
                    List<Double> breathDatas = JsonUtils.jsonToList(radarUserDataFourTmp.getBs(), Double.class);
                    if (breathDatas != null) {
                        breathPhaseData.addAll(breathDatas);
                    }
                    List<Double> heartDatas = JsonUtils.jsonToList(radarUserDataFourTmp.getHs(), Double.class);
                    if (heartDatas != null) {
                        heartPhaseData.addAll(heartDatas);
                    }
                }
                realTimeDataVOV4.setBreathPhaseData(breathPhaseData);
                realTimeDataVOV4.setHeartPhaseData(heartPhaseData);
                realTimeDataVOV4.setBreathBpm(radarUserDataFour.getBrebp());
                realTimeDataVOV4.setHeartBpm(radarUserDataFour.getHRBpRe());
            }
            if (TCFg == 0 && OBFg == 0) {
//                List<Double> heartPhaseData = new ArrayList<>(200);
//                List<Double> breathPhaseData = new ArrayList<>(200);
//                for (int i = 0;i<radarUserDataList.size();i++) {
//                    RadarUserDataFour radarUserDataFourTmp = radarUserDataList.get(radarUserDataList.size()-1 - i);
//                    List<Double> breathDatas = JsonUtils.jsonToList(radarUserDataFourTmp.getBs(), Double.class);
//                    if (breathDatas != null) {
//                        breathPhaseData.addAll(breathDatas);
//                    }
//                    List<Double> heartDatas = JsonUtils.jsonToList(radarUserDataFourTmp.getHs(), Double.class);
//                    if (heartDatas != null) {
//                        heartPhaseData.addAll(heartDatas);
//                    }
//                }
//                realTimeDataVOV4.setBreathPhaseData(breathPhaseData);
//                realTimeDataVOV4.setHeartPhaseData(heartPhaseData);
//                realTimeDataVOV4.setBreathBpm(radarUserDataFour.getBrebp());
//                realTimeDataVOV4.setHeartBpm(radarUserDataFour.getHRBpRe());
//                realTimeDataVOV4.setFrameNo(radarUserDataFour.getFrameNo());
                //实时呼吸率和心率新增状态判断，
                //初版可以就按可调的阈值范围来做判断
                //默认：
                //晚20:00～早08:00
                //心率：45～90
                //呼吸率：8～24
                //其他时间：
                //心率：60～100
                //呼吸率：12～20
                //算法可以传过来这个人是否是配合的状态，非配合的情况下，不显示条上定位的圆圈
                //获取当前机构 呼吸心率 数值  白天

//                Integer tenantId = RecoupUtil.getCurrentUser().getTenantId();
                /*List<RealTimeMonitoring> realTimeMonitorings = realTimeMonitoringService.getBaseMapper().selectList(Wrappers
                        .<RealTimeMonitoring>lambdaQuery()
                        .eq(RealTimeMonitoring::getTenantId, tenantId));*/

                List<RealTimeMonitoring> realTimeMonitorings = realTimeMonitoringService.getRealTimeMonitoring("RealTimeMonitoring-" + tenantId.toString());

                realTimeMonitorings.forEach(f -> {
                    if (1 == f.getMonitorType() && 1 == f.getEnable()) {
                        LocalTime nowTime = LocalTime.now();
                        LocalDate nowDate = LocalDate.now();
                        LocalTime startTime = LocalTime.parse(f.getStartTime());
                        LocalTime endTime = LocalTime.parse(f.getEndTime());
                        if (startTime.isBefore(endTime)) {
                            // 开始和结束时间在同一天
                            if (nowTime.isAfter(startTime) && nowTime.isBefore(endTime)) {
                                if (radarUserDataFour.getBrebp() > Integer.parseInt(f.getStartBpm()) && radarUserDataFour.getBrebp() < Integer.parseInt(f.getEndBpm())) {
                                    //正常
                                    realTimeDataVOV4.setBreathStatus("1");
                                } else if (radarUserDataFour.getBrebp() < Integer.parseInt(f.getStartBpm())) {
                                    //过慢
                                    realTimeDataVOV4.setBreathStatus("0");
                                } else if (radarUserDataFour.getBrebp() > Integer.parseInt(f.getEndBpm())) {
                                    //过快
                                    realTimeDataVOV4.setBreathStatus("2");
                                }
                            }
                        } else {
                            LocalDateTime nowDateTime = LocalDateTime.of(nowDate, nowTime);
                            LocalDateTime startDateTime = LocalDateTime.of(nowDate, startTime);
                            LocalDateTime endDateTime = LocalDateTime.of(nowDate.plusDays(1), endTime);
                            // 结束时间在后一天
                            if (nowDateTime.isAfter(startDateTime) && nowDateTime.isBefore(endDateTime)) {
                                if (radarUserDataFour.getHRBpRe() > Integer.parseInt(f.getStartBpm()) && radarUserDataFour.getHRBpRe() < Integer.parseInt(f.getEndBpm())) {
                                    //正常
                                    realTimeDataVOV4.setBreathStatus("1");
                                } else if (radarUserDataFour.getHRBpRe() < Integer.parseInt(f.getStartBpm())) {
                                    //过慢
                                    realTimeDataVOV4.setBreathStatus("0");
                                } else if (radarUserDataFour.getHRBpRe() > Integer.parseInt(f.getEndBpm())) {
                                    //过快
                                    realTimeDataVOV4.setBreathStatus("2");
                                }
                            }
                            // 开始时间在前一天
                            startDateTime = LocalDateTime.of(nowDate.minusDays(1), startTime);
                            endDateTime = LocalDateTime.of(nowDate, endTime);
                            if (nowDateTime.isAfter(startDateTime) && nowDateTime.isBefore(endDateTime)) {
                                if (radarUserDataFour.getHRBpRe() > Integer.parseInt(f.getStartBpm()) && radarUserDataFour.getHRBpRe() < Integer.parseInt(f.getEndBpm())) {
                                    //正常
                                    realTimeDataVOV4.setBreathStatus("1");
                                } else if (radarUserDataFour.getHRBpRe() < Integer.parseInt(f.getStartBpm())) {
                                    //过慢
                                    realTimeDataVOV4.setBreathStatus("0");
                                } else if (radarUserDataFour.getHRBpRe() > Integer.parseInt(f.getEndBpm())) {
                                    //过快
                                    realTimeDataVOV4.setBreathStatus("2");
                                }
                            }
                        }
                    } else if (2 == f.getMonitorType() && 1 == f.getEnable()) {
                        LocalTime nowTime = LocalTime.now();
                        LocalDate nowDate = LocalDate.now();
                        LocalTime startTime = LocalTime.parse(f.getStartTime());
                        LocalTime endTime = LocalTime.parse(f.getEndTime());
                        if (startTime.isBefore(endTime)) {
                            // 开始和结束时间在同一天
                            if (nowTime.isAfter(startTime) && nowTime.isBefore(endTime)) {
                                if (radarUserDataFour.getBrebp() > Integer.parseInt(f.getStartBpm()) && radarUserDataFour.getBrebp() < Integer.parseInt(f.getEndBpm())) {
                                    //正常
                                    realTimeDataVOV4.setHeartStatus("1");
                                } else if (radarUserDataFour.getBrebp() < Integer.parseInt(f.getStartBpm())) {
                                    //过慢
                                    realTimeDataVOV4.setHeartStatus("0");
                                } else if (radarUserDataFour.getBrebp() > Integer.parseInt(f.getEndBpm())) {
                                    //过快
                                    realTimeDataVOV4.setHeartStatus("2");
                                }
                            }
                        } else {
                            LocalDateTime nowDateTime = LocalDateTime.of(nowDate, nowTime);
                            LocalDateTime startDateTime = LocalDateTime.of(nowDate, startTime);
                            LocalDateTime endDateTime = LocalDateTime.of(nowDate.plusDays(1), endTime);
                            // 结束时间在后一天
                            if (nowDateTime.isAfter(startDateTime) && nowDateTime.isBefore(endDateTime)) {
                                if (radarUserDataFour.getBrebp() > Integer.parseInt(f.getStartBpm()) && radarUserDataFour.getBrebp() < Integer.parseInt(f.getEndBpm())) {
                                    //正常
                                    realTimeDataVOV4.setHeartStatus("1");
                                } else if (radarUserDataFour.getBrebp() < Integer.parseInt(f.getStartBpm())) {
                                    //过慢
                                    realTimeDataVOV4.setHeartStatus("0");
                                } else if (radarUserDataFour.getBrebp() > Integer.parseInt(f.getEndBpm())) {
                                    //过快
                                    realTimeDataVOV4.setHeartStatus("2");
                                }
                            }
                            // 开始时间在前一天
                            startDateTime = LocalDateTime.of(nowDate.minusDays(1), startTime);
                            endDateTime = LocalDateTime.of(nowDate, endTime);
                            if (nowDateTime.isAfter(startDateTime) && nowDateTime.isBefore(endDateTime)) {
                                if (radarUserDataFour.getBrebp() > Integer.parseInt(f.getStartBpm()) && radarUserDataFour.getBrebp() < Integer.parseInt(f.getEndBpm())) {
                                    //正常
                                    realTimeDataVOV4.setHeartStatus("1");
                                } else if (radarUserDataFour.getBrebp() < Integer.parseInt(f.getStartBpm())) {
                                    //过慢
                                    realTimeDataVOV4.setHeartStatus("0");
                                } else if (radarUserDataFour.getBrebp() > Integer.parseInt(f.getEndBpm())) {
                                    //过快
                                    realTimeDataVOV4.setHeartStatus("2");
                                }
                            }
                        }
                    }

                });


            }
            realTimeDataVOV4.setFrameNo(radarUserDataFour.getFrameNo());
            // 1 表示过近，0 表示正常
            realTimeDataVOV4.setTCFg(TCFg);
            realTimeDataVOV4.setOBFg(OBFg);
            realTimeDataVOV4.setAAFg(radarUserDataList.get(0).getAAFg());
            // 1 表示配合，0 表示非配合
            realTimeDataVOV4.setTSFg(radarUserDataList.get(0).getTSFg());
            //判断是否是网络不好。默认0是网络好 1是网络不好
            realTimeDataVOV4.setIsRadarNetwork(bedRadarBO.getIsRadarNetwork());
            realTimeDataVOV4.setIsRadarOnline(bedRadarBO.getIsRadarOnline());
        }
        //判断是否是首次通电的雷达设备  如果是首次通电没有版本号默认是0。如果通过电有版本号1。
        if (null != bedRadarBO.getRadarVersion()) {
            realTimeDataVOV4.setIsElectrify(1);
        } else {
            realTimeDataVOV4.setIsElectrify(0);
        }
        //判断是否是连续0或者255  0正常 1不正常
        if (radarUserDataList60 != null && radarUserDataList60.size() == 3) {
            List<Double> ss = new ArrayList<>();
            for (int i = 0; i < radarUserDataList60.size(); i++) {
                String temp = radarUserDataList60.get(i);
                ss.addAll(JsonUtils.jsonToList(temp, Double.class));
            }
            double couns = ss.stream().mapToDouble(t -> t).sum();
            if (couns == 7650 || couns == 0.0) {
                realTimeDataVOV4.setDeviceType("1");
            } else {
                realTimeDataVOV4.setDeviceType("0");
            }
        } else {
            realTimeDataVOV4.setDeviceType("0");
        }
        realTimeDataVOV4.setVersion(4);
        return realTimeDataVOV4;
    }


    private void setStatus(Bed bed, RealTimeDataVOV4 realTimeDataVOV4) {
        if (bed.getIsRadarOnline() == Bed.RADAR_OFFLINE) {  //离线
            realTimeDataVOV4.setStatus(STATUS_RADAR_OFFLINE);
        } else if (bed.getIsRadarOn() == Bed.RADAR_OFF) {  //关闭
            realTimeDataVOV4.setStatus(STATUS_MONITOR_OFF);
        } else if (bed.getStatus() == Bed.STATUS_ALARM) {
            this.setStatusOutBed(bed, realTimeDataVOV4);
            realTimeDataVOV4.setOutBedAlarm(true);
        } else if (bed.getStatus() == Bed.STATUS_NORMAL) {
            realTimeDataVOV4.setOutBedAlarm(false);
            switch (bed.getSubStatus()) {
                case Bed.SUB_STATUS_OUT_BED:
                    this.setStatusOutBed(bed, realTimeDataVOV4);
                    break;
                case Bed.SUB_STATUS_CLEAR:
                    realTimeDataVOV4.setStatus(STATUS_NORMAL);
                    realTimeDataVOV4.setSubStatus(SUB_STATUS_CLEAR);
                    break;
                case Bed.SUB_STATUS_LIGHT_SLEEP:
                    realTimeDataVOV4.setStatus(STATUS_NORMAL);
                    realTimeDataVOV4.setSubStatus(SUB_STATUS_LIGHT);
                    break;
                case Bed.SUB_STATUS_DEEP_SLEEP:
                    realTimeDataVOV4.setStatus(STATUS_NORMAL);
                    realTimeDataVOV4.setSubStatus(SUB_STATUS_DEEP);
                    break;
                default:
                    log.warn("setStatus 不支持的子状态 bed:{}", bed);
            }
        } else {
            log.warn("setStatus 不支持的状态 bed:{}", bed);
        }
    }

    /**
     * 设置离床状态
     *
     * @param bed
     * @param realTimeDataVO
     */
    private void setStatusOutBed(Bed bed, RealTimeDataVOV4 realTimeDataVO) {
        realTimeDataVO.setStatus(STATUS_OUT_BED);
        LocalDateTime happenTime = bed.getHappenTime();
        long duration = System.currentTimeMillis() / 1000 - happenTime.toEpochSecond(ZoneOffset.of("+8"));
        realTimeDataVO.setDuration((int) duration);
    }
}
